using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Shard.Contracts.SqlSugarConnect;
using Shared.SqlSugarCore;
using Shared.SqlSugarCore.Helper;
using SqlSugar;
using Volo.Abp.Data;

namespace UserService.SqlSugarCore;

[DependsOn(typeof(SqlSugarModule))]
public class UserServiceSqlSugarCoreModule : SqlSugarModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
    }
    
    public override async Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context)
    {
        var service = context.ServiceProvider;
        //配置文件
        var options = service.GetRequiredService<IOptions<DbConnOptions>>().Value;
        //日志
        var logger = service.GetRequiredService<ILogger<SqlSugarModule>>();

        StringBuilder sb = new StringBuilder();
        sb.AppendLine();
        sb.AppendLine("==========IM-UserService-SQL配置:==========");
        sb.AppendLine($"数据库连接字符串：{options.Url}");
        sb.AppendLine($"数据库类型：{options.DbType.ToString()}");
        sb.AppendLine($"是否开启种子数据：{options.EnabledDbSeed}");
        sb.AppendLine($"是否开启CodeFirst：{options.EnabledCodeFirst}");
        sb.AppendLine($"是否开启Saas多租户：{options.EnabledSaasMultiTenancy}");
        sb.AppendLine("===========================================");

        logger.LogInformation(sb.ToString());

        if (options.EnabledCodeFirst)
        {
            
            
            CodeFirst(service);
        }

        if (options.EnabledDbSeed)
        {
            await DataSeedAsync(service);
        }
    }

    //种子数据 在各个微服务去实现 IDataSeeder
    private async Task DataSeedAsync(IServiceProvider service)
    {
        var dataSeeder = service.GetRequiredService<IDataSeeder>();
        await dataSeeder.SeedAsync();
    }
    
    private void CodeFirst(IServiceProvider service)
    {
        var db = service.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient;
        //创建数据库
        db.DbMaintenance.CreateDatabase();
        // 显式加载领域层程序集
        var domainAssembly = Assembly.Load("UserService.Domain"); // 替换为实际的领域层程序集名称
        // 获取当前微服务的实体类型
        var entityTypes = domainAssembly.GetTypes()
            .Where(type => type.GetCustomAttribute<SugarTable>() != null);
        
        SqlSugarCodeFirstHelper.InitTables(db, entityTypes);
    }
}